class Middleware {
  constructor(name, autoRun = true) {
    this.name = name;
    this.autoRun = autoRun;
  }

  async execute(context, next) {
    console.log(`执行中间件: ${this.name}`);
    await next();
  }
}

class MiddlewareExecutor {
  constructor() {
    this.middlewares = [];
  }

  use(middleware) {
    this.middlewares.push(middleware);
  }

  async executeAll(context) {
    let currentIndex = -1;

    const next = async () => {
      currentIndex++;
      if (currentIndex < this.middlewares.length) {
        const middleware = this.middlewares[currentIndex];
        if (middleware.autoRun) {
          await middleware.execute(context, next);
        } else {
          await next();
        }
      }
    };

    await next();
  }
}

// 创建中间件执行器实例
const executor = new MiddlewareExecutor();

// 定义默认中间件 A、B 和 C
const middlewareA = new Middleware('Middleware A');
const middlewareB = new Middleware('Middleware B');
const middlewareC = new Middleware('Middleware C', false);

// 将默认中间件 A、B 添加到执行器中
executor.use(middlewareA);
executor.use(middlewareB);

// 模拟请求处理
const handleRequest = async () => {
  const context = {};

  // 执行默认中间件 A、B
  await executor.executeAll(context);

  // 用户定义和运行自定义中间件
  const userMiddleware = new Middleware('运行时加载用户自定义中间件(插件)');
  await userMiddleware.execute(context, async () => {
    console.log('User Middleware - Next');
  });
};

// 处理请求
handleRequest().then(() => {
  console.log('请求结束');
});

